#include <framework/framework_i.h>

static char buf[RL_BUFLEN];

#ifndef NULL
#define NULL ((void *)0)
#endif

char *
readline(const char *prompt)
{
	 int i, c, echoing;

	 if (prompt != NULL)
		  cprintf("%s", prompt);

	 i = 0;
	 echoing = iscons(0);
	 while (1) {
		  c = getchar();
		  if (c < 0) {
			   cprintf("read error: %e\n", c);
			   return NULL;
		  } else if (c >= ' ' && i < RL_BUFLEN-1) {
			   if (echoing)
					cputchar(c);
			   buf[i++] = c;
		  } else if (c == '\b' && i > 0) {
			   if (echoing)
					cputchar(c);
			   i--;
		  } else if (c == '\n' || c == '\r') {
			   if (echoing)
					cputchar(c);
			   buf[i] = 0;
			   return buf;
		  }
	 }
}

static void
putch(int ch, int *cnt)
{
	 cputchar(ch);
	 *cnt++;
}

int
vcprintf(const char *fmt, va_list ap)
{
	 int cnt = 0;

	 vprintfmt((void*)putch, &cnt, fmt, ap);
	 return cnt;
}

int
cprintf(const char *fmt, ...)
{
	 va_list ap;
	 int cnt;

	 va_start(ap, fmt);
	 cnt = vcprintf(fmt, ap);
	 va_end(ap);

	 return cnt;
}

int io_console_enabled;
int io_log_enabled;

static spin_lock_t io_lock;

// kpipe_t log_pipe __attribute__ ((aligned (PAGE_SIZE)));

void io_init()
{
	 io_console_enabled = 0;
	 io_log_enabled = 0;

	 cons_init();
}

int
vkprintf(const char *fmt, va_list ap)
{
	 if (io_console_enabled == 0 &&
		 io_log_enabled == 0) return 0;

	 uint32_t flags = irq_save();
		  
	 
	 if (io_console_enabled)
		  vcprintf(fmt, ap);
	 
	 if (io_log_enabled)
	 {
		  // vkpprintf(&log_pipe, fmt, ap);
	 }

	 irq_restore(flags);

	 return 0;
}

int
kprintf(const char *fmt, ...)
{
	 va_list ap;
	 int cnt;

	 va_start(ap, fmt);
	 cnt = vkprintf(fmt, ap);
	 va_end(ap);

	 return cnt;
}
